package org.example.onlinejudge.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * 登出控制器
 * 负责处理用户登出请求
 * 实现逻辑：
 * 1. 提供GET方式的logout接口，避免使用POST方式导致的session问题
 * 2. 清除用户的SecurityContext，完成登出操作
 * 3. 重定向到登录页面，并附加logout=true参数，提示用户已成功登出
 */
@Controller
public class LogoutController {

    /**
     * GET方式的logout（用于链接点击）
     */
    @GetMapping("/perform_logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return "redirect:/login";
    }
}

